﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace ManagoMes.Read.API.Applications.ProductionWorkOrders
{
    public class InventoryHander : IRequestHandler<InventoryCommand, PageDTO<InventoryListDTO>>
    {
        private readonly IBateRepository<InventoryListDTO> inventory;

        public InventoryHander(IBateRepository<InventoryListDTO> inventory)
        {
            this.inventory = inventory;
        }

        public async Task<PageDTO<InventoryListDTO>> Handle(InventoryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                PageDTO<InventoryListDTO> res=new PageDTO<InventoryListDTO>();
                InventoryListDTO dto=new InventoryListDTO();
                DapperHelper dapper=new DapperHelper();
                string sql = @"select a.productManageNode,a.productManageName,a.StickWorkNum,a.StockWorkTime,b.unites,b.productManageNumber,c.StashName FROM stockremoval a 
                               JOIN productmanage b ON a.productManageNode=b.productManageNode JOIN
                               warehouselist c ON a.WarehouseId=c.StashId where 1=1 ";
                if (!string.IsNullOrEmpty(request.productManageNode))
                {
                    sql += " and a.productManageNode like '%" + request.productManageNode + "%'";
                }
                if (!string.IsNullOrEmpty(request.productManageName))
                {
                    sql += " and a.productManageName like '%" + request.productManageName + "%'";
                }
                if (!string.IsNullOrEmpty(request.StashName))
                {
                    sql += " and c.StashName like '%" + request.StashName + "%'";
                }
                if (request.StockWorkTime!=null)
                {
                    sql += $" and a.StockWorkTime = '{request.StockWorkTime}' ";
                }
                var list = inventory.GetAll(sql, dto,dapper.MangoMesRead).ToList();
                res.TotalCount = list.Count;
                res.PageCount =(int)Math.Ceiling(res.TotalCount * 1.0 / request.PageSize);
                res.Data=list.OrderBy(x=>x.productManageNode).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                return res;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
